package com.leTest.eduService.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leTest.eduService.entity.Subject.OneSubject;
import com.leTest.eduService.entity.Subject.TwoSubject;
import com.leTest.eduService.entity.SubjectEntity;
import com.leTest.eduService.entity.excel.SubjectData;
import com.leTest.eduService.listener.SubjectExcelListener;
import com.leTest.eduService.mapper.SubjectMapper;
import com.leTest.eduService.service.SubjectService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author le
 * @since 2025-02-13
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, SubjectEntity> implements SubjectService {

    @Override
    public void saveSubject(MultipartFile file, SubjectService subjectService) {
        try {
            //1.得到文件输入流
            InputStream in = file.getInputStream();

            //2.调用方法进行读取
            EasyExcel
                    .read(
                            in,
                            SubjectData.class,
                            new SubjectExcelListener(subjectService))
                    .sheet()
                    .doRead();
        } catch(Exception e) {
        }
    }

    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        QueryWrapper<SubjectEntity> wrapperOne = new QueryWrapper<>();
        wrapperOne.eq("parent_id", "0");
        List<SubjectEntity> oneSubject = baseMapper.selectList(wrapperOne);

        QueryWrapper<SubjectEntity> wrapperTwo = new QueryWrapper<>();
        wrapperTwo.ne("parent_id", "0");
        List<SubjectEntity> twoSubject = baseMapper.selectList(wrapperTwo);

        List<OneSubject> resultSubjectList = new ArrayList<>();

        for (SubjectEntity subjectEntity : oneSubject) {
            OneSubject resOneSubject = new OneSubject();
            BeanUtils.copyProperties(subjectEntity, resOneSubject);

            List<TwoSubject> resTwoSubjectList =  new ArrayList<>();
            for (SubjectEntity subjectEntityTwo : twoSubject) {
                if (subjectEntityTwo.getParentId().equals(subjectEntity.getId())) {
                    TwoSubject resTwoSubject = new TwoSubject();
                    BeanUtils.copyProperties(subjectEntityTwo, resTwoSubject);
                    resTwoSubjectList.add(resTwoSubject);
                }
            }

            resOneSubject.setChildren(resTwoSubjectList);
            resultSubjectList.add(resOneSubject);
        }

        return resultSubjectList;
    }
}
